package top.lyunz.fangkeji.controller.wechat;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.EncodeException;

import top.lyunz.fangkeji.bean.selfHelpRegistration;
import top.lyunz.fangkeji.bean.travelRecordsBean;

import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.pl.REGON;
import org.hibernate.validator.internal.util.privilegedactions.GetAnnotationAttribute;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import net.coobird.thumbnailator.Thumbnails;
import top.lyunz.fangkeji.bean.AppointmentAuditselt;
import top.lyunz.fangkeji.bean.AppointmentRecord;
import top.lyunz.fangkeji.bean.AppointmentRecordAdd;
import top.lyunz.fangkeji.bean.AttendanceConfig;
import top.lyunz.fangkeji.bean.AttendanceConfigAdd;
import top.lyunz.fangkeji.bean.AttendanceRecord;
import top.lyunz.fangkeji.bean.ClockInForDetails;
import top.lyunz.fangkeji.bean.Company;
import top.lyunz.fangkeji.bean.Equipment;
import top.lyunz.fangkeji.bean.Fuser;
import top.lyunz.fangkeji.bean.TravelRecords;
import top.lyunz.fangkeji.bean.appointmentMember;
import top.lyunz.fangkeji.bean.companyAdd;
import top.lyunz.fangkeji.bean.getAttendanceRecord;
import top.lyunz.fangkeji.bean.loginToChoose;
import top.lyunz.fangkeji.bean.pageselect;
import top.lyunz.fangkeji.bean.registeruser;
import top.lyunz.fangkeji.bean.selAttendanceRecord;
import top.lyunz.fangkeji.bean.unreviewed;
import top.lyunz.fangkeji.bean.userAdd;
import top.lyunz.fangkeji.controller.web.web;
import top.lyunz.fangkeji.service.AppointmentRecordService;
import top.lyunz.fangkeji.service.AttendanceConfigService;
import top.lyunz.fangkeji.service.AttendanceRecordService;
import top.lyunz.fangkeji.service.TravelRecordsService;
import top.lyunz.fangkeji.service.appointmentMemberService;
import top.lyunz.fangkeji.service.companyService;
import top.lyunz.fangkeji.service.equipmentService;
import top.lyunz.fangkeji.service.fuserService;
import top.lyunz.fangkeji.tools.SimpleResult;
import top.lyunz.fangkeji.tools.WanNianLi;
import top.lyunz.fangkeji.tools.baiduyun;
import top.lyunz.fangkeji.tools.delFile;
import top.lyunz.fangkeji.tools.img;
import top.lyunz.fangkeji.tools.imgproc;
import top.lyunz.fangkeji.webSocketSerevice.WebSocketServer;
@Controller
@RequestMapping("/wechat")
public class wechatController {
    static Logger logger= LoggerFactory.getLogger(wechatController.class);

	@Resource
	private AppointmentRecordService AppointmentRecordService;
	@Resource
	private fuserService fuserService;
	@Resource
	private companyService companyService;
	/**
	 * 发起邀请
	 * @param add
	 * @return
	 */
	@RequestMapping("/initiateInvitation")
	public @ResponseBody SimpleResult initiateInvitation(AppointmentRecordAdd add) {
		String[] geteSn = add.geteSn();
		String eSn="";
		if (geteSn != null) {
			for (int i = 0; i < geteSn.length; i++) {
				if (i == geteSn.length - 1) {
					eSn += geteSn[i];
				} else {
					eSn = eSn + geteSn[i] + "-";
				}
			}
		}
		else
		{
			eSn = "default";
		}
		String apDate = add.getApDate();
		String apBegin = add.getApBegin();
		String apEnd = add.getApEnd();
		String apName = add.getApName();
		Integer apNum = add.getApNum();
		String apTel = add.getApTel();
		String apReason = add.getApReason();
		Integer uid = add.getUid();
		Fuser fuserByuId = fuserService.getFuserByuId(uid);
		Company companyByCid = companyService.getCompanyByCid(fuserByuId.getcId());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String date = df.format(new Date());
		String apIdentity=System.currentTimeMillis() + "";
		int is=AppointmentRecordService.addAppointmentRecord(new AppointmentRecord(null, apDate, apBegin, apEnd, companyByCid.getcAddress(), apNum, apName, apTel, apReason, uid, date, 1, eSn,  apIdentity));
		if (is>0) {
			 AppointmentRecord appointmentRecordByApIdentity = AppointmentRecordService.getAppointmentRecordByApIdentity(apIdentity);
			 return new SimpleResult(appointmentRecordByApIdentity);
		}else {
			return new SimpleResult(false);
		}
	}
	
	
	/**
	 * 注册获取手机验证码
	 * 
	 * @param tel
	 * @return
	 */
	@RequestMapping("/invitationAndAppointmentGetCode/{tel}")
	public @ResponseBody SimpleResult invitationAndAppointmentGetCode(@PathVariable("tel") String tel) {
		// sms s=new sms();
					// String mobileQuery = s.mobileQuery(tel);
		SimpleResult result;
		String code=tel;
		result = new SimpleResult(code);
		return result;
	}
	@Resource
	private appointmentMemberService appointmentMemberService;
	/**
	 * 完善邀请
	 * @param add
	 * @return
	 * @throws IOException
	 * @throws EncodeException 
	 */
	@RequestMapping("/doAddAppointmentMember")
	public @ResponseBody SimpleResult invitationPerfection(AppointmentRecordAdd add) throws IOException, EncodeException {
		String apTel = add.getApTel();
		Integer apId = add.getApId();
		String apName = add.getApName();
		MultipartFile file = add.getuImg();
		String originalFilename = file.getOriginalFilename();
		String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
		img img = new img();
		String timeString = System.currentTimeMillis() + "";
		String Img = timeString + prefix;
		String newImg = timeString + "-thumbnail" + prefix;
		img.uploadingImg(file, Img);
		Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
		delFile delFile = new delFile();
		delFile.del(web.imgurlpath, Img);
		AppointmentRecord appointmentRecordByapId = AppointmentRecordService.getAppointmentRecordByapId(apId);
		Fuser fuser = new Fuser(null, apName, "123456", apTel, newImg, 4, 1, 0, 0, appointmentRecordByapId.geteSn());
		baiduyun baiduyun = new baiduyun();
		Integer baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
		if(baiduyunAPI==null) {
			return new SimpleResult("001", "没有检测到人脸", null);
		}else {
			if(baiduyunAPI!=1) {
				delFile.del(web.imgurlpath, newImg);
				return new SimpleResult("002", "检测到多张人脸", null);
			}else {
				if (appointmentMemberService.getByapId(apId).size()!=appointmentRecordByapId.getApNum()) {
				List<Fuser> byuTel = fuserService.getByuTel(apTel);
				if (byuTel==null) {
					int is = fuserService.fuserAdd(fuser);
					if (is>0) {
						List<Fuser> u = fuserService.getByuTel(apTel);
						int isadd= appointmentMemberService.addAppointmentMember(new appointmentMember(null, apId, u.get(0).getuId()));
						 AppointmentRecord app = AppointmentRecordService.getAppointmentRecordByapId(apId);
						AppointmentRecord appointmentRecord=new AppointmentRecord();
						appointmentRecord.setApName(apName);
						if(app.getApTel()==null||app.getApTel().equals("")) {
							appointmentRecord.setApTel(apTel);
						}
						appointmentRecord.setApId(apId);
						AppointmentRecordService.updAppointmentRecord(appointmentRecord);
						
						  String apAddress = app.getApAddress();
						  String apBegin = app.getApBegin();
						  String apDate = app.getApDate();
						  String apEnd = app.getApEnd();
						  String apIdentity = app.getApIdentity();
						  Integer apNum = app.getApNum();
						  String apReason = app.getApReason();
						  Integer apStatus = app.getApStatus();
						  String creationTime = app.getCreationTime();
						  Integer uid = app.getUid();
						  List<Fuser> user = fuserService.getByuTel(apTel);
						  String getuImg = user.get(0).getuImg();
						  AppointmentAuditselt adds = new AppointmentAuditselt(apId, apDate, apBegin, apEnd, apAddress, apNum, apName, apTel, apReason, uid, creationTime, apStatus, null, apIdentity, null, null, getuImg);
						  //消息推送
						  
							String geteSn = u.get(0).geteSn();
							String getuName = u.get(0).getuName();
							String[] st=geteSn.split("-");
							for (int i = 0; i < st.length; i++) {
								String str="{typr:'adduser',uId:"+uid+",'uName':"+getuName+",'uImg:'"+getuImg+",'apDate:'"+apDate+",'apBegin:'"+apBegin+",'apEnd:'"+apEnd+"}";
								boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
							}
						  						  
						  return new SimpleResult(true);
					}
				}else {
					String geteSn = appointmentRecordByapId.geteSn();
					byuTel.get(0).seteSn(geteSn);
					int isupd=fuserService.updateFuser(byuTel.get(0));
					int isadd= appointmentMemberService.addAppointmentMember(new appointmentMember(null, apId, byuTel.get(0).getuId()));
					return new SimpleResult("003", "注册失败", null);
				}
			}else {
				return new SimpleResult("003", "该预约已达到人数上限", null);
			}
			}
		}
		return null;
	}
	/**
	 * 查询单个邀请信息
	 * @param apid
	 * @return
	 */
	@RequestMapping("/toAddAppointmentMember/{apid}")
	public @ResponseBody SimpleResult toAddAppointmentMember(@PathVariable("apid") int apid) {
		
		return new SimpleResult(AppointmentRecordService.getAppointmentRecordByapId(apid));
	}
	/**
	 * 发起预约
	 * @param add
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/initiateAppointment")
	public @ResponseBody SimpleResult initiateAppointment(AppointmentRecordAdd add) throws IOException {
		String apTel = add.getApTel();
		String apName = add.getApName();
		MultipartFile file = add.getuImg();
		String apDate = add.getApDate();
		String apBegin = add.getApBegin();
		Integer apNum = add.getApNum();
		String apReason = add.getApReason();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String date = df.format(new Date());
		String apIdentity=System.currentTimeMillis() + "";
		String apEnd = add.getApEnd();
		String getuTel = add.getuTel();
		String sn = null;
		if(add.geteSn()!=null)
			sn = StringUtils.join(add.geteSn());
		else
			sn = "default";
		List<Fuser> users = fuserService.getByuTel(getuTel);
		if(users==null)
		{
			return new SimpleResult("001", "接待人不存在！", null);
		}

		Fuser user = users.get(0);
		
		List<Fuser> apuser = fuserService.getByuTel(apTel);
		if(apuser == null)
		{
			String filepath = imgproc.saveimg(file);
			if(filepath == null)
			{
				return new SimpleResult("002", "照片没有上传或上传失败！", null);
			}
			
			int faceret = imgproc.detectface(web.imgurlpath+filepath);
			if(faceret == 1)
			{
				return new SimpleResult("003", "照片没有检测到人脸！", null);
			}
			else if(faceret == 2){
				return new SimpleResult("003", "照片检测到多张人脸！", null);
			}
			
			apuser.add(new Fuser(null, apName, "123456", apTel, filepath, 5, 1, 0, 0, sn));
			if(apuser == null)
			{
				return new SimpleResult("004", "创建访客失败！", null);
			}
			int isfuseradd = fuserService.fuserAdd(apuser.get(0));
			if(isfuseradd>0)
			{
				
			}
		}
		
		Integer uid = user.getuId();
		Company companyByCid = companyService.getCompanyByCid(user.getcId());
		if(companyByCid == null)
		{
			return new SimpleResult("006", "接待人公司信息错误！", null);
		}
		
		AppointmentRecord ar = new AppointmentRecord(null, apDate, apBegin, apEnd, companyByCid.getcAddress(), apNum, apName, apTel, apReason, uid, date, 2, sn,  apIdentity);
		int is=AppointmentRecordService.addAppointmentRecord(ar);
		if (is==0) {
			return new SimpleResult("005", "添加预约记录失败！", null);
		}
		
		return new SimpleResult(true);
	}
	/**
	 * 获取被预约人名下公司
	 * @param tel
	 * @return
	 */
	@RequestMapping("/getByusertel/{tel}")
	public @ResponseBody SimpleResult getByusertel(@PathVariable("tel") String tel){
		List<Fuser> user = fuserService.getByuTel(tel);
		List<loginToChoose> loginToChoose = new ArrayList<loginToChoose>();
		for (Fuser uFuser : user) {
			Company companyByCid = companyService.getCompanyByCid(uFuser.getcId());
			loginToChoose.add(new loginToChoose(uFuser.getuId(), companyByCid.getcName()));
		}
		return new SimpleResult(user);
	}
		/**
		 * 查询单个预约信息
		 * @param apid
		 * @param model
		 * @return
		 */
	  @RequestMapping("/toAppointmentAudit/{apid}")
	  public @ResponseBody SimpleResult toAppointmentAudit(@PathVariable("apid") Integer apid,Model model) {
		  AppointmentRecord app = AppointmentRecordService.getAppointmentRecordByapId(apid);
		  String apAddress = app.getApAddress();
		  String apBegin = app.getApBegin();
		  String apDate = app.getApDate();
		  String apEnd = app.getApEnd();
		  String apIdentity = app.getApIdentity();
		  String apName = app.getApName();
		  Integer apNum = app.getApNum();
		  String apReason = app.getApReason();
		  Integer apStatus = app.getApStatus();
		  String apTel = app.getApTel();
		  String creationTime = app.getCreationTime();
		  Integer uid = app.getUid();
		  List<Fuser> user = fuserService.getByuTel(apTel);
		  String getuImg = user.get(0).getuImg();
		  AppointmentAuditselt add = new AppointmentAuditselt(apid, apDate, apBegin, apEnd, apAddress, apNum, apName, apTel, apReason, uid, creationTime, apStatus, null, apIdentity, null, null, getuImg);
		  return new SimpleResult(app);
	  }
	  /**
	   * 预约信息审核
	   * @param auditselt
	   * @return
	 * @throws EncodeException 
	 * @throws IOException 
	   */
	  @RequestMapping("/doAppointmentAudit")
	  public @ResponseBody SimpleResult doAppointmentAudit(AppointmentAuditselt auditselt) throws IOException, EncodeException {
		  String[] geteSn = auditselt.geteSn();
		  String eSn="";
			if (geteSn != null) {
				for (int i = 0; i < geteSn.length; i++) {
					if (i == geteSn.length - 1) {
						eSn += geteSn[i];
					} else {
						eSn = eSn + geteSn[i] + "-";
					}
				}
			}
			int is = AppointmentRecordService.updAppointmentRecord(new AppointmentRecord(auditselt.getApId(), null, null, null, null, null, null, null, null, null, null, 1, eSn, null));
			if (is>0) {
				 AppointmentRecord app = AppointmentRecordService.getAppointmentRecordByapId(auditselt.getApId());
				  String apAddress = app.getApAddress();
				  String apBegin = app.getApBegin();
				  String apDate = app.getApDate();
				  String apEnd = app.getApEnd();
				  String apIdentity = app.getApIdentity();
				  String apName = app.getApName();
				  Integer apNum = app.getApNum();
				  String apReason = app.getApReason();
				  Integer apStatus = app.getApStatus();
				  String apTel = app.getApTel();
				  String creationTime = app.getCreationTime();
				  Integer uid = app.getUid();
				  List<Fuser> user = fuserService.getByuTel(apTel);
				  String getuImg = user.get(0).getuImg();
				  AppointmentAuditselt add = new AppointmentAuditselt(auditselt.getApId(), apDate, apBegin, apEnd, apAddress, apNum, apName, apTel, apReason, uid, creationTime, apStatus, null, apIdentity, null, null, getuImg);
				  //访客信息推送
					String[] st=eSn.split("-");
					for (int i = 0; i < st.length; i++) {
						String str="{typr:'adduser',uId:"+uid+",'uName':"+apName+",'uImg:'"+getuImg+",'apDate:'"+apDate+",'apBegin:'"+apBegin+",'apEnd:'"+apEnd+"}";
						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
					}

				  return new SimpleResult(true);
			}else {
				return new SimpleResult(false);
			}
	  }
	  /**
	   * 查询所以未审核预约信息
	   * @param uid
	   * @return
	   */
	  @RequestMapping("/getUnreviewedAppointmentRecord/{uid}")
	  public @ResponseBody SimpleResult getUnreviewedAppointmentRecord(@PathVariable("uid") int uid) {
		  List<AppointmentRecord> unreviewedAppointmentRecord = AppointmentRecordService.getUnreviewedAppointmentRecord(uid);
		  return new SimpleResult(unreviewedAppointmentRecord);
	  }
	  /**
	   * 查询未审核预约数量
	   * @param uid
	   * @return
	   */
	  @RequestMapping("/getUnreviewedAppointmentRecordNum/{uid}")
	  public @ResponseBody SimpleResult getUnreviewedAppointmentRecordNum(@PathVariable("uid") int uid) {
		  List<AppointmentRecord> unreviewedAppointmentRecord = AppointmentRecordService.getUnreviewedAppointmentRecord(uid);
		  int size = unreviewedAppointmentRecord.size();
		  unreviewed unreviewed= new unreviewed(size);
		  return new SimpleResult(unreviewed);
	  }
	  /**
	   * 查询所有拜访记录
	   * @param uid
	   * @return
	   */
	  @RequestMapping("/getcompletedAppointmentRecord/{uid}")
	  public @ResponseBody SimpleResult getcompletedAppointmentRecord(@PathVariable("uid") int uid) {
		  Fuser fuserByuId = fuserService.getFuserByuId(uid);
		  SimpleResult simpleResult = new SimpleResult(null);
		  if(fuserByuId.getuIdentity()!=4) {
			  List<AppointmentRecord> getcompletedAppointmentRecord = AppointmentRecordService.getcompletedAppointmentRecord(uid);
			  simpleResult.setData(getcompletedAppointmentRecord);
			  return simpleResult;
		  }else {
			  List<AppointmentRecord> list = new ArrayList<AppointmentRecord>();
			  List<appointmentMember> byUid = appointmentMemberService.getByUid(uid);
			  for (appointmentMember app : byUid) {
				Integer apId = app.getApId();
				AppointmentRecord appointmentRecordByapId = AppointmentRecordService.getAppointmentRecordByapId(apId);
				if (appointmentRecordByapId.getApStatus()==3) {
					list.add(appointmentRecordByapId);
				}
				
			}
			  simpleResult.setData(list);
			  return simpleResult;
		  }
		
	  }
	  /**
	   * 查询所有预约记录
	   * @param uId
	   * @return
	   */
	  @RequestMapping("/getallAppointmentRecord/{uId}")
	  public @ResponseBody SimpleResult getallAppointmentRecord(@PathVariable("uId") int uId) {
		  Fuser fuserByuId = fuserService.getFuserByuId(uId);
		  SimpleResult simpleResult = new SimpleResult(null);
		  if(fuserByuId.getuIdentity()!=4) {
			  List<AppointmentRecord> getcompletedAppointmentRecord = AppointmentRecordService.getallAppointmentRecord(uId);
			  simpleResult.setData(getcompletedAppointmentRecord);
			  return simpleResult;
		  }else {
			  List<AppointmentRecord> list = new ArrayList<AppointmentRecord>();
			  List<appointmentMember> byUid = appointmentMemberService.getByUid(uId);
			  for (appointmentMember app : byUid) {
				Integer apId = app.getApId();
				AppointmentRecord appointmentRecordByapId = AppointmentRecordService.getAppointmentRecordByapId(apId);
				if (appointmentRecordByapId.getApStatus()==1) {
					list.add(appointmentRecordByapId);
				}
				
			}
			  simpleResult.setData(list);
			  return simpleResult;
		  }
	  }
	  
	  /**
	   * 查询所有预约记录
	   * @param uId
	   * @return
	   */
	  @RequestMapping("/getviAppointmentRecord/{uId}")
	  public @ResponseBody SimpleResult getviAppointmentRecord(@PathVariable("uId") int uId) {
		  Fuser fuserByuId = fuserService.getFuserByuId(uId);
		  SimpleResult simpleResult = new SimpleResult(null);
		  List<AppointmentRecord> getcompletedAppointmentRecord = AppointmentRecordService.getviAppointmentRecord(uId);
		  simpleResult.setData(getcompletedAppointmentRecord);
		  return simpleResult;
	  }
	  
	  /**
	   * 查询预约记录
	   * @param uId
	   * @return
	   */
	  @RequestMapping("/getAppointmentsbyapTel/{apTel}")
	  public @ResponseBody SimpleResult getAppointmentsbyapTel(@PathVariable("apTel") String apTel) {
		  //Fuser fuserByuId = fuserService.getFuserByuId(apTel);
		  SimpleResult simpleResult = new SimpleResult(null);
		  List<AppointmentRecord> getcompletedAppointmentRecord = AppointmentRecordService.getAppointmentsbyapTel(apTel);
		  simpleResult.setData(getcompletedAppointmentRecord);
		  return simpleResult;
	  }
	  
	  /**
	   * 开门
	   */
	  @Resource
	  private equipmentService equipmentService;
	  @RequestMapping("/toopenDoor/{eSn}")
	  public @ResponseBody SimpleResult openDoor(@PathVariable("eSn") String eSn) {
		  Equipment equipment= new Equipment();
		  equipment.setsN(eSn);
		  equipment.seteDoorStatus(1);
		  int updEquipmentByesN = equipmentService.updEquipmentByesN(equipment);
		  return new SimpleResult(updEquipmentByesN>0?true:false);
	  }
	  /**
	   * 自助注册
	   * @param selfHelpRegistration
	   * @return
	   * @throws IOException
	   */
	  @RequestMapping("/selfHelpRegistration")
	  public @ResponseBody SimpleResult selfHelpRegistration(selfHelpRegistration selfHelpRegistration) throws IOException {
			MultipartFile uImg = selfHelpRegistration.getuImg();
			String uName = selfHelpRegistration.getuName();
			String uTel = selfHelpRegistration.getuTel();
			String getuPwd = selfHelpRegistration.getuPwd();
			Integer cid = selfHelpRegistration.getCid();
			img img = new img();
			String newImg;
			delFile delFile = new delFile();
			String timeString = System.currentTimeMillis() + "";

			String originalFilename = uImg.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			String Img = timeString + prefix;
			newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(uImg, Img);
			Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
			delFile.del(web.imgurlpath, Img);
			baiduyun baiduyun= new baiduyun();
			Integer baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
			if (baiduyunAPI==null) {
				return new SimpleResult("001", "没有检测到人脸", null);
			} else {
				if (baiduyunAPI != 1) {
					delFile.del(web.imgurlpath, newImg);
					return new SimpleResult("001", "检测到多张人脸", null);
				} else {
						
						Fuser fuser = new Fuser(null, uName, getuPwd, uTel, newImg, 3, 2, cid,0 , null);
						int isfuseradd = fuserService.fuserAdd(fuser);
						if (isfuseradd > 0) {
							return new SimpleResult(true);
						} else {
							return new SimpleResult(false);
						}
					} 
				}
	  } 
	  /*
	   * 查询所有未审核自助注册
	   */
	  @RequestMapping("/unreviewedFuser/{cId}")
	  public @ResponseBody SimpleResult unreviewedFuser(@PathVariable("cId") int cId) {
		  List<Fuser> allUnreviewedFuser = fuserService.getAllUnreviewedFuser(cId);
		  return new SimpleResult(allUnreviewedFuser); 
	  }
	  /*
	   * 查询未审核的条数
	   */
	  @RequestMapping("/unreviewedFuserNum/{cId}")
	  public @ResponseBody SimpleResult unreviewedFuserNum(@PathVariable("cId") int cId) {
		  List<Fuser> allUnreviewedFuser = fuserService.getAllUnreviewedFuser(cId);
		  int size = allUnreviewedFuser.size();
		  unreviewed unreviewed = new unreviewed(size);
		  return new SimpleResult(unreviewed);
	  }
	  /**
	   * 查询所有绑定当前设备的公司
	   * @param eSn
	   * @return
	   */
	  @RequestMapping("/getAllAuthorizationCompanyByeSn/{eSn}")
	  public @ResponseBody SimpleResult getAllAuthorizationCompanyByeSn(@PathVariable("eSn") String eSn) {
		  List<Company> allAuthorizationCompanyByeSn = companyService.getAllAuthorizationCompanyByeSn(eSn);
		  return new SimpleResult(allAuthorizationCompanyByeSn);
	  }
	  /**
	   * 获取指定自助注册
	   * @param uid
	   * @return
	   */
	  @RequestMapping("/toauditselfHelpRegistration/{uid}")
	  public @ResponseBody SimpleResult auditselfHelpRegistration (@PathVariable("uid") int uid) {
		  	
		  	return new SimpleResult(fuserService.getFuserByuId(uid));
	  }
	  /**
	   * 审核自助注册
	   * @param add
	   * @return
	 * @throws EncodeException 
	 * @throws IOException 
	   */
	  @RequestMapping("/doauditselfHelpRegistration")
	  public @ResponseBody SimpleResult doauditselfHelpRegistration(userAdd add) throws IOException, EncodeException {
		  String[] geteSn = add.geteSn();
		  String eSn="";
		  if (geteSn != null) {
				for (int i = 0; i < geteSn.length; i++) {
					if (i == geteSn.length - 1) {
						eSn += geteSn[i];
					} else {
						eSn = eSn + geteSn[i] + "-";
					}
				}
			}
		  Fuser fuser= new Fuser();
		  fuser.seteSn(eSn);
		  fuser.setuStatus(1);
		  fuser.setuId(add.getuId());
		  int is = fuserService.updateFuser(fuser);
		  List<Fuser> byuTel = fuserService.getByuTel(add.getuTel());
			String getuName = fuser.getuName();
			String getuImg = fuser.getuImg();
			for (int i = 0; i < geteSn.length; i++) {
				String str="{typr:'adduser',uId:"+byuTel.get(0).getcId()+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
				boolean sendInfo = WebSocketServer.sendInfo(str, geteSn[i]);
			}
		  return new SimpleResult(is>0?true:false);
		  
		  
	  }
	  

		/**
		 * 主管理员注册
		 * 
		 * @param registeruser
		 * @param response
		 * @param session
		 * @param model
		 * @return
		 * @throws IOException
		 */
		@RequestMapping("/userregister")
		public @ResponseBody SimpleResult userregister(registeruser registeruser,  HttpSession session,
				Model model) throws IOException {
			String uName = registeruser.getuName();
			String uPwd = registeruser.getuPwd();
			String uTel = registeruser.getuTel();
			MultipartFile file = registeruser.getuImg();
			String originalFilename = file.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			img img = new img();
			String timeString = System.currentTimeMillis() + "";
			String Img = timeString + prefix;
			String newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(file, Img);
			Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
			delFile delFile = new delFile();
			delFile.del(web.imgurlpath, Img);
			Fuser fuser = new Fuser(null, uName, uPwd, uTel, newImg, registeruser.getuIdentity(), 0, 0, 0, null);
			baiduyun baiduyun = new baiduyun();
			Integer baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
			String cName = registeruser.getcName();
			System.currentTimeMillis();
			String cAddress = registeruser.getcAddress();
			List<Company> companys = companyService.getCompaniesByCname(cName);
			Company company = new Company(null, cName, cAddress, "company.jpg", 0, timeString, 0, null);

			if(companys!=null&&companys.size()>0)
			{
				company = companys.get(0);
			}
			else {
				if (companyService.companyAdd(company) > 0) {
					company = companyService.getCompanyBycIdentity(timeString);
					companyService.updCompany(
							new Company(company.getcId(), null, null, null, 0, null, company.getcId(), null));
				}
				else {
					return new SimpleResult("005", "添加公司失败！", null);
				}
			}
			
			if (baiduyunAPI==null) {
				return new SimpleResult("001", "没有检测到人脸", null);
			} else {
				if (baiduyunAPI != 1) {
					delFile.del(web.imgurlpath, newImg);
					return new SimpleResult("002", "检测到多张人脸", null);
				} else {
					fuser.setcId(company.getcId());
					int isfuseradd = fuserService.fuserAdd(fuser);
					if (isfuseradd > 0) {
						Fuser uFuser = fuserService.getFuserByCidAndUtel(new Fuser(null, null, null, uTel, null, null, null, company.getcId(), null, null));
						fuser.setParentLevel(uFuser.getuId());
						fuserService.updateFuser(uFuser);
						fuserService.updbByuTel(new Fuser(null, null, uPwd, uTel, null, null, null, null, null, null));
						return  new SimpleResult(true);
					} else {
						companyService.delByCid(company.getcId());
						return new SimpleResult("003", "注册失败", null);
					}
				}
			}

		}

		/**
		 * 注册获取手机验证码
		 * 
		 * @param tel
		 * @return
		 */
		@RequestMapping("/verificationCode/{tel}")
		public @ResponseBody SimpleResult verificationCode(@PathVariable("tel") String tel) {

			SimpleResult result;
				// sms s=new sms();
				// String mobileQuery = s.mobileQuery(tel);
			result = new SimpleResult(tel);
			return result;
		}

		/**
		 * 忘记密码获取手机验证码
		 * 
		 * @param tel
		 * @return
		 */
		@RequestMapping("/updpwdverificationCode/{tel}")
		public @ResponseBody SimpleResult updpwdverificationCode(@PathVariable("tel") String tel) {

			SimpleResult result;
				// sms s=new sms();
				// String mobileQuery = s.mobileQuery(tel);
			result = new SimpleResult(tel);
			return result;
		}
		
		/**
		 * 登录
		 * @param fuser
		 * @param session
		 * @return
		 * @throws IOException
		 */
		@RequestMapping("/dologin")
		public @ResponseBody  SimpleResult dologin(Fuser fuser, HttpSession session) throws IOException {
			logger.info("dologin : user tel:"+fuser.getuTel());

			List<Fuser> user = fuserService.getFuserGetbyTelAndUpwd(fuser);
			if (user.size() > 1) {
				List<loginToChoose> loginToChoose = new ArrayList<loginToChoose>();
				for (Fuser uFuser : user) {
					Company companyByCid = companyService.getCompanyByCid(uFuser.getcId());
					loginToChoose.add(new loginToChoose(uFuser.getuId(), companyByCid.getcName()));
				}
				SimpleResult sr = new SimpleResult(loginToChoose);
				sr.setMessage("1");
				return sr;
			} else if(user.size()==1){
				logger.info("dologin get: user tel:"+user.get(0).getuTel());
				session.setAttribute("user", user.get(0));
				SimpleResult sr = new SimpleResult(user.get(0));
				sr.setMessage("0");
				return sr;
			}else {
				logger.info("dologin : user null");
				return new SimpleResult(false);
			}
		}
		
		@RequestMapping("/dologinToChoose")
		public  @ResponseBody  SimpleResult dologinToChoose(loginToChoose choose,HttpSession session) {
			int uid = choose.getUid();
			Fuser user = fuserService.getFuserByuId(uid);
			session.setAttribute("user", user);
			return new SimpleResult(user);
		}
		
		/**
		 * 忘记密码
		 * 
		 * @param fuser
		 * @param response
		 * @param model
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/doupdpwd")
		public @ResponseBody SimpleResult doupdpwd(Fuser fuser) throws Exception {
			int is = fuserService.updbByuTel(fuser);
			if (is > 0) {
				return new SimpleResult(true);
			}else {
				return new SimpleResult(false);
			}
		
		}

		/**
		 * 设备分页查询
		 * 
		 * @param cid
		 * @param page
		 * @return
		 */
		@RequestMapping("/getPageEquipments/{cid}/{page}")
		public @ResponseBody SimpleResult getPageEquipments(@PathVariable("cid") int cid, @PathVariable("page") int page) {
			List<Equipment> arr = equipmentService.getAllEquipments(cid);
			int size = arr.size();
			int pageindex = 0;
			int pagemax;
			if (size % 30 == 0) {
				pagemax = size / 30;
			} else {
				pagemax = size / 30 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) * 30;
			List<Equipment> pagearr = equipmentService.getByPageEquipments(new pageselect(pageindex, 30, null, cid));
			return new SimpleResult(pagearr, pagemax);
		}
		
		/**
		 * 设备分页查询
		 * 
		 * @param cid
		 * @param page
		 * @return
		 */
		@RequestMapping("/getAllEquipmentsByCid/{cid}")
		public @ResponseBody SimpleResult getAllEquipmentsByCid(@PathVariable("cid") int cid) {
			List<Equipment> arr = equipmentService.getAllEquipments(cid);
			if(arr==null)
			{
				return new SimpleResult("001", "没发现此公司设备！", null);
			}
			else 
			{
				return new SimpleResult(arr);
			}
		}


		/**
		 * 添加设备
		 * 
		 * @param equipment
		 * @param response
		 * @param session
		 * @return
		 * @throws IOException
		 */
		@RequestMapping("/addEquipments")
		public @ResponseBody SimpleResult addEquipments(Equipment equipment,  HttpSession session)
				throws IOException {

			Equipment obj = equipmentService.getEquipmentBySn(equipment.getsN());
			Fuser user = (Fuser) session.getAttribute("user");
			if(user == null)
			{
				return new SimpleResult("002", "用户没有登陆！", null);
			}
			if (obj == null) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
				String date = df.format(new Date());
				equipment.setActivationTime(date);
				equipment.setFinalHeartbeatTime(null);
				equipment.setcId(user.getcId());
				equipment.seteStatus(0);
				equipment.seteLivingBodyStatus(0);
				int isadd = equipmentService.equipmentAdd(equipment);
				if (isadd > 0) {
					user.setuStatus(1);
					
					Equipment eq = equipmentService.getEquipmentBySn(equipment.getsN());
					Fuser fuserByuId = fuserService.getFuserByuId(user.getuId());
					user.seteSn( fuserByuId.geteSn()+"-"+ eq.getsN());
					fuserService.updateFuser(user);
					equipmentService.updEquipmentByesN(new Equipment(null, null, null, null, null, equipment.getsN(), null, 0, 0, 0, 1, 0,0));
					return new SimpleResult(true);
				} else {
					return new SimpleResult(false);
				}
			} else {
			/*
			 * if (obj.getcId() == user.getcId()) { equipmentService.updEquipmentByeId(new
			 * Equipment(obj.geteId(), null, null, null, null, null,
			 * null,null,null,null,null,null,null)); return new SimpleResult(true); }else {
			 */
					return new SimpleResult("001", "设备已被注册", null);
				//}
			}
		}

		/**
		 * 根据设备ID删除设备，实际上是修改设备状态
		 * 
		 * @param eid
		 * @return
		 */
		@RequestMapping("/delEquipments/{eid}")
		public @ResponseBody SimpleResult delEquipments(@PathVariable("eid") int eid) {
			int is = equipmentService.updEquipmentByeId(new Equipment(eid, null, null, null, null, null, null, 2,null,null,null,null,null));
			return new SimpleResult(is > 0 ? true : false);

		}

		/**
		 * 根据设备ID查询单个设备
		 * 
		 * @param eid
		 * @param model
		 * @return
		 */
		@RequestMapping("/toupdEquipments/{eid}")
		public @ResponseBody  SimpleResult toupdEquipments(@PathVariable("eid") int eid) {
			 return new SimpleResult(equipmentService.getEquipmentByeId(eid));
		}

		/**
		 * 修改单个设备
		 * 
		 * @param equipment
		 * @param response
		 * @return
		 * @throws IOException
		 */
		@RequestMapping("/doupdEquipments")
		public @ResponseBody SimpleResult doupdEquipments(Equipment equipment, HttpServletResponse response) throws IOException {
			int is = equipmentService.updEquipmentByeId(equipment);
			if (is > 0) {
				return new SimpleResult(true);
			} else {
				return new SimpleResult(false);
			}

		}

		/**
		 * 公司分页查询
		 * 
		 * @param page
		 * @param session
		 * @return
		 */
		@RequestMapping("/getPageCompany/{page}")
		public @ResponseBody SimpleResult getPageCompany(@PathVariable("page") int page, HttpSession session) {
			Fuser user = (Fuser) session.getAttribute("user");
			List<Company> arr = new ArrayList<Company>();
			List<Company> comarr = new ArrayList<Company>();
			if (user.getuIdentity() == 0) {
				arr = companyService.getCompaniesByParentLevel(user.getcId());
			} else if (user.getuIdentity() == 1) {
				arr.add(companyService.getCompanyByCid(user.getcId()));
			}
			int size = arr.size();
			int pageindex = 0;
			int pagemax;
			if (size % 20 == 0) {
				pagemax = size / 20;
			} else {
				pagemax = size / 20 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) * 20;
			if (user.getuIdentity() == 0) {
				comarr = companyService.getCompaniesBypage(new pageselect(pageindex, 20, null, user.getcId()));
				return new SimpleResult(comarr, pagemax);
			} else if (user.getuIdentity() == 1) {
				return new SimpleResult(arr, pagemax);
			} else {
				return null;
			}

		}

		/**
		 * 冻结公司
		 * 
		 * @param cid
		 * @return
		 * @throws EncodeException 
		 * @throws IOException 
		 */
		@RequestMapping("/pauseCompany/{cid}")
		public @ResponseBody SimpleResult pauseCompany(@PathVariable("cid") int cid) throws IOException, EncodeException {
			int is = companyService.updCompany(new Company(cid, null, null, null, 1, null, null, null));
			if (is > 0) {
				fuserService.batchUpdEidByCid(new Fuser(null, null, null, null, null, null, 2, cid, null, null));
				List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(cid);
				for (Fuser fuser : fusersAllByCid) {
					Integer getuId = fuser.getuId();
					String geteSn = fuser.geteSn();
					String getuName = fuser.getuName();
					String getuImg = fuser.getuImg();
					String[] st=geteSn.split("-");
					for (int i = 0; i < st.length; i++) {
						String str="{typr:'deluser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
					}
				}
				
			}
			return new SimpleResult(is > 0 ? true : false);
		}

		/**
		 * 恢复公司状态
		 * 
		 * @param cid
		 * @return
		 * @throws EncodeException 
		 * @throws IOException 
		 */
		@RequestMapping("/recoverCompany/{cid}")
		public @ResponseBody SimpleResult recoverCompany(@PathVariable("cid") int cid) throws IOException, EncodeException {
			int is = companyService.updCompany(new Company(cid, null, null, null, 0, null, null, null));
			if (is > 0) {
				Company companyByCid = companyService.getCompanyByCid(cid);
				List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(cid);
				for (Fuser fuser : fusersAllByCid) {
					Integer getuId = fuser.getuId();
					String geteSn = fuser.geteSn();
					String getuName = fuser.getuName();
					String getuImg = fuser.getuImg();
					String[] st=geteSn.split("-");
					for (int i = 0; i < st.length; i++) {
						String str="{typr:'adduser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
					}
				}
			}
			return new SimpleResult(is > 0 ? true : false);
		}

		/**
		 * 添加公司
		 * 
		 * @param companyAdd
		 * @param session
		 * @param response
		 * @return
		 * @throws IOException
		 */
		@RequestMapping("/companyAdd")
		public @ResponseBody SimpleResult company_add(companyAdd companyAdd, HttpSession session, HttpServletResponse response)
				throws IOException {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter writer = response.getWriter();
			MultipartFile cImg = companyAdd.getcImg();
			String cName = companyAdd.getcName();
			String cAddress = companyAdd.getcAddress();
			String[] geteId = companyAdd.geteSn();
			String eId = "";
			if (geteId != null) {
				for (int i = 0; i < geteId.length; i++) {
					if (i == geteId.length - 1) {
						eId += geteId[i];
					} else {
						eId = eId + geteId[i] + "-";
					}
				}
			}
			img img = new img();
			String newImg;
			delFile delFile = new delFile();
			String timeString = System.currentTimeMillis() + "";
			if (!cImg.isEmpty()) {
				String originalFilename = cImg.getOriginalFilename();
				String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
				String Img = timeString + cName + prefix;
				newImg = timeString + "-thumbnail" + prefix;
				img.uploadingImg(cImg, Img);
				Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
				delFile.del(web.imgurlpath, Img);
			} else {
				newImg = "company.jpg";
			}
			Fuser user = (Fuser) session.getAttribute("user");
			int is = companyService
					.companyAdd(new Company(null, cName, cAddress, newImg, 0, timeString, user.getcId(), eId));
			if (is > 0) {
				return new SimpleResult(true);
			} else {
				delFile.del(web.imgurlpath, newImg);
				return new SimpleResult(false);
			}

		}

		@RequestMapping("/companytoUpd/{cid}")
		public @ResponseBody SimpleResult companytoUpd(@PathVariable("cid") int cid) {
			return new SimpleResult(companyService.getCompanyByCid(cid));
		}
		/**
		 * 公司修改
		 * @param companyAdd
		 * @param response
		 * @return
		 * @throws IOException
		 * @throws EncodeException 
		 */
		@RequestMapping("/companytdoUpd")
		public @ResponseBody SimpleResult companytdoUpd(companyAdd companyAdd) throws IOException, EncodeException {
			MultipartFile cImg = companyAdd.getcImg();
			String cName = companyAdd.getcName();
			String cAddress = companyAdd.getcAddress();
			String[] geteId = companyAdd.geteSn();
			int cid = companyAdd.getcId();
			Company companyByCid = companyService.getCompanyByCid(cid);

			String eId = "";
			if (geteId != null) {
				for (int i = 0; i < geteId.length; i++) {
					if (i == geteId.length - 1) {
						eId += geteId[i];
					} else {
						eId = eId + geteId[i] + "-";
					}
				}
			}
			img img = new img();
			String newImg;
			delFile delFile = new delFile();
			String timeString = System.currentTimeMillis() + "";
			if (!cImg.isEmpty()) {
				String originalFilename = cImg.getOriginalFilename();
				String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
				String Img = timeString + prefix;
				newImg = timeString + "-thumbnail" + prefix;
				img.uploadingImg(cImg, Img);
				Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
				delFile.del(web.imgurlpath, Img);
				String getcImg = companyByCid.getcImg();
				delFile.del(web.imgurlpath, getcImg);
			} else {
				newImg = null;
			}
			int is = companyService.updCompany(new Company(cid, cName, cAddress, newImg, null, null, null, eId));

			if (is > 0) {
				
				List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(cid);
				for (Fuser fuser : fusersAllByCid) {
					Integer getuId = fuser.getuId();
					String geteSn = fuser.geteSn();
					String getuName = fuser.getuName();
					String getuImg = fuser.getuImg();
					String[] st=geteSn.split("-");
					for (int i = 0; i < st.length; i++) {
						String str="{typr:'deluser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
					}
					
				}
				int iss=fuserService.batchUpdEidByCid(new Fuser(null, null, null, null, null, null, 1, cid, null, eId));
				for (Fuser fuser : fusersAllByCid) {
					Integer getuId = fuser.getuId();
					String geteSn = fuser.geteSn();
					String getuName = fuser.getuName();
					String getuImg = fuser.getuImg();
					String[] st=geteSn.split("-");
					for (int i = 0; i < st.length; i++) {
						String str="{typr:'adduser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
					}
				}
				return new SimpleResult(true);
			} else {
				delFile.del(web.imgurlpath, newImg);
				return new SimpleResult(false);
			}
		}

		@RequestMapping("/getPageuser/{page}")
		public @ResponseBody SimpleResult getPageuser(@PathVariable("page") int page, HttpSession session) {
			Fuser user = (Fuser) session.getAttribute("user");
			List<Fuser> arr = new ArrayList<Fuser>();
			List<Fuser> fusersAllBy = fuserService.getFusersAllByCid(user.getcId());
			int size = fusersAllBy.size();
			int pageindex = 0;
			int pagemax;
			if (size % 20 == 0) {
				pagemax = size / 20;
			} else {
				pagemax = size / 20 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) * 20;
			arr = fuserService.getFuserBypage(new pageselect(pageindex, 20, null, user.getcId()));
			return new SimpleResult(arr, pagemax);
		}

		@RequestMapping("/deluser/{uid}")
		public @ResponseBody SimpleResult deluser(@PathVariable int uid) {
			int delFuser = fuserService.delFuser(uid);
			
			return new SimpleResult(delFuser > 0 ? true : false);
		}

		@RequestMapping("/douserAdd")
		public @ResponseBody SimpleResult douserAdd(userAdd userAdd, HttpSession session) throws IOException, EncodeException {
			MultipartFile uImg = userAdd.getuImg();
			String uName = userAdd.getuName();
			String uTel = userAdd.getuTel();
			String[] geteId = userAdd.geteSn();
			String eId = "";
			if (geteId != null) {
				for (int i = 0; i < geteId.length; i++) {
					if (i == geteId.length - 1) {
						eId += geteId[i];
					} else {
						eId = eId + geteId[i] + "-";
					}
				}
			}
			img img = new img();
			String newImg;
			delFile delFile = new delFile();
			String timeString = System.currentTimeMillis() + "";

			String originalFilename = uImg.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			String Img = timeString + prefix;
			newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(uImg, Img);
			Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
			delFile.del(web.imgurlpath, Img);
			baiduyun baiduyun= new baiduyun();
			Integer baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
			if (baiduyunAPI==null) {
				return new SimpleResult("001", "没有检测到人脸", null);
			} else {
				if (baiduyunAPI != 1) {
					delFile.del(web.imgurlpath, newImg);
					return new SimpleResult("002", "检测到多张人脸", null);
				} else {
						Fuser user=(Fuser)session.getAttribute("user");
						Fuser fuser = new Fuser(null, uName, "123456", uTel, newImg, userAdd.getuIdentity(), 1, user.getcId(), user.getuId(), eId);
						int isfuseradd = fuserService.fuserAdd(fuser);
						if (isfuseradd > 0) {
								Integer getuId = fuser.getuId();
								String geteSn = fuser.geteSn();
								String getuName = fuser.getuName();
								String getuImg = fuser.getuImg();
								String[] st=geteSn.split("-");
								for (int i = 0; i < st.length; i++) {
									String str="{typr:'adduser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
									boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
								}
							return new SimpleResult(true);
						} else {
							return new SimpleResult("003", "注册失败", null);
						}
					} 
				}
		}
		/**
		 * 获取单个用户信息
		 * @param uId
		 * @param model
		 * @return
		 */
		@RequestMapping("/usertoupd/{uId}")
		public @ResponseBody SimpleResult usertoupd (@PathVariable("uId") int uId,Model model) {
			Fuser fuserByuId = fuserService.getFuserByuId(uId);
			return new SimpleResult(fuserByuId);
		}
		/**
		 * 修改用户信息
		 * @param userAdd
		 * @return
		 * @throws IOException
		 * @throws EncodeException
		 */
		@RequestMapping("/userdoupd")
		public @ResponseBody SimpleResult userdoupd (userAdd userAdd) throws IOException, EncodeException {
			Fuser olduser=fuserService.getFuserByuId(userAdd.getuId());
			boolean change = false;
			boolean ret = false;
			if(!olduser.getuName().equals(userAdd.getuName()))
			{
				olduser.setuName(userAdd.getuName());
				change = true;
			}
			
			if(!olduser.getuTel().equals(userAdd.getuTel()))
			{
				olduser.setuTel(userAdd.getuTel());
				change = true;
			}
		
			
			if(null!=userAdd.getuImg())
			{
				MultipartFile uImg = userAdd.getuImg();
				if (!uImg.isEmpty()) {
					String newImg;
					delFile delFile = new delFile();
					img img = new img();
					String getcImg = olduser.getuImg();
					String timeString = System.currentTimeMillis() + "";
					String originalFilename = uImg.getOriginalFilename();
					String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
					String Img = timeString + prefix;
					newImg = timeString + "-thumbnail" + prefix;
					img.uploadingImg(uImg, Img);
					Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
					delFile.del(web.imgurlpath, Img);
					delFile.del(web.imgurlpath, getcImg);
					baiduyun baiduyun= new baiduyun();
					Integer baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
					if (baiduyunAPI==null) {
						//delFile.del(web.imgurlpath, newImg);
						return new SimpleResult("001", "没有检测到人脸", null);
					} else {
						if (baiduyunAPI != 1) {
							delFile.del(web.imgurlpath, newImg);
							return new SimpleResult("002", "检测到多张人脸", null);
						} 
					}
					olduser.setuImg(newImg);
					change = true;
				}
			}	
			
			if(change)
			{
				int is = fuserService.updateFuser(olduser);
				if (is > 0) {
					ret = true;
				}
			}
			
			if(ret)
				return new SimpleResult(true);
			
			return new SimpleResult(false);
			
//			String uName = userAdd.getuName();
//			String uTel = userAdd.getuTel();
//			String[] geteId = userAdd.geteId();
//			int uIdentity=userAdd.getuIdentity();
//			String eId = "";
//			int uId=userAdd.getuId();
//			Fuser olduser=fuserService.getFuserByuId(uId);
//			if (geteId != null) {
//				for (int i = 0; i < geteId.length; i++) {
//					if (i == geteId.length - 1) {
//						eId += geteId[i];
//					} else {
//						eId = eId + geteId[i] + "-";
//					}
//				}
//			}
//			img img = new img();
//			String newImg;
//			delFile delFile = new delFile();
//			String timeString = System.currentTimeMillis() + "";
//			if (!uImg.isEmpty()) {
//				String originalFilename = uImg.getOriginalFilename();
//				String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
//				String Img = timeString + prefix;
//				newImg = timeString + "-thumbnail" + prefix;
//				img.uploadingImg(uImg, Img);
//				Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
//				delFile.del(web.imgurlpath, Img);
//				String getcImg = olduser.getuImg();
//				delFile.del(web.imgurlpath, getcImg);
//			} else {
//				newImg = null;
//			}
//			baiduyun baiduyun= new baiduyun();
//			JSONObject baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
//			if (baiduyunAPI.isNull("result")) {
//				return new SimpleResult("001", "没有检测到人脸", null);
//			} else {
//				JSONObject c = baiduyunAPI.getJSONObject("result");
//				int face_num = (int) c.get("face_num");
//				if (face_num != 1) {
//					delFile.del(web.imgurlpath, newImg);
//					return new SimpleResult("002", "检测到多张人脸", null);
//				} else {
//					Fuser fuser= fuserService.getFuserByuId(uId);
//					Integer getuId = fuser.getuId();
//					String geteSn = fuser.geteSn();
//					String getuName = fuser.getuName();
//					String getuImg = fuser.getuImg();
//					String[] st=geteSn.split("-");
//					for (int i = 0; i < st.length; i++) {
//						String str="{typr:'deluser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
//						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
//					}
//					int is = fuserService.updateFuser(new Fuser(uId, uName, null, uTel, newImg, uIdentity, 1, null, null, eId));
//					if (is > 0) {
//
//							for (int i = 0; i < geteId.length; i++) {
//								String str="{typr:'adduser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
//								boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
//							}
//						return new SimpleResult(true);
//					} else {
//						new SimpleResult("003", "修改失败", null);
//					}
//						}
//					}
//		return null; 
		}
		/**
		 * 获取考勤设置
		 */
		@Resource
		private AttendanceConfigService AttendanceConfigService;
		@RequestMapping("/getAttendanceSetting")
		public @ResponseBody SimpleResult getAttendanceSetting (HttpSession session) {
			Fuser att = (Fuser)session.getAttribute("user");
			AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(att.getcId());
			return new SimpleResult(attendanceConfigByCid);
			
		}
		/**
		 * 更新考勤设置
		 * @param config
		 * @param session
		 * @param response
		 * @return
		 * @throws IOException
		 * @throws EncodeException 
		 */
		@RequestMapping("/attendanceSetting")
		public @ResponseBody  SimpleResult attendanceSetting(AttendanceConfigAdd config,HttpSession session,HttpServletResponse response) throws IOException, EncodeException {
			response.setContentType("text/html;charset=utf-8");
			Fuser user=(Fuser)session.getAttribute("user");
			AttendanceConfig oldattendanceConfig =AttendanceConfigService.getAttendanceConfigByCid(user.getcId());
			String[] workdayarr = config.getWorkday();
			String workday="";
		
			 for (int i = 0; i < workdayarr.length; i++) {
				if (i==workdayarr.length-1) {
					workday+=workdayarr[i];
				}else {
					workday=workday+workdayarr[i]+"-";
				}
			}
			
			AttendanceConfig attendanceConfig= new AttendanceConfig(null, config.getAttendanceTime(),config.getClosingTime(), workday, user.getcId());
			if (oldattendanceConfig==null) {
				AttendanceConfigService.addAttendanceConfig(attendanceConfig);
				Company companyByCid = companyService.getCompanyByCid(user.getcId());
				String geteSn = companyByCid.geteSn();
				String[] st=geteSn.split("-");
				for (int i = 0; i < st.length; i++) {
					String str="{typr:'addattendanceSetting',attendanceTime:"+config.getAttendanceTime()+",'closingTime':"+config.getClosingTime()+",'workday:'"+workday+",'cId':"+user.getcId()+"}";
					boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
				}
				return new SimpleResult(true);
			}else {
				attendanceConfig.setAcId(oldattendanceConfig.getAcId());
				AttendanceConfigService.updAttendanceConfig(attendanceConfig);
				Company companyByCid = companyService.getCompanyByCid(user.getcId());
				String geteSn = companyByCid.geteSn();
				String[] st=geteSn.split("-");
				for (int i = 0; i < st.length; i++) {
					String str="{'typr':updattendanceSetting,attendanceTime:"+config.getAttendanceTime()+",'closingTime':"+config.getClosingTime()+",'workday:'"+workday+",'cId':"+user.getcId()+"}";
					boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
				}

				return new SimpleResult(true);
			}
			
		}
		/**
		 * 获取个人信息
		 * @param session
		 * @return
		 */
		@RequestMapping("/getpersonalDetails")
		public @ResponseBody SimpleResult  personalDetails(HttpSession session ) {
			Fuser user=(Fuser)session.getAttribute("user");
			Fuser fuser= fuserService.getFuserByuId(user.getuId());
			return new SimpleResult(fuser) ;
		}
		/**
		 * 修改个人信息
		 * @param userAdd
		 * @param response
		 * @return
		 * @throws IOException
		 * @throws EncodeException 
		 */
		@RequestMapping("/setpersonalDetails")
		public @ResponseBody SimpleResult setpersonalDetails (userAdd userAdd) throws IOException, EncodeException {
			MultipartFile uImg = userAdd.getuImg();
			String uName = userAdd.getuName();
			String uTel = userAdd.getuTel();
			int uId=userAdd.getuId();
			Fuser olduser=fuserService.getFuserByuId(uId);
			img img = new img();
			String newImg;
			delFile delFile = new delFile();
			String timeString = System.currentTimeMillis() + "";
			if (!uImg.isEmpty()) {
				String originalFilename = uImg.getOriginalFilename();
				String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
				String Img = timeString + prefix;
				newImg = timeString + "-thumbnail" + prefix;
				img.uploadingImg(uImg, Img);
				Thumbnails.of(web.imgurlpath + Img).scale(1f).outputQuality(0.5f).toFile(web.imgurlpath + newImg);
				delFile.del(web.imgurlpath, Img);
				String getcImg = olduser.getuImg();
				delFile.del(web.imgurlpath, getcImg);
			} else {
				newImg = null;
			}
			baiduyun baiduyun= new baiduyun();
			Integer baiduyunAPI = baiduyun.baiduyunAPI(web.imgurlpath + newImg);
			if (baiduyunAPI==null) {
				return new SimpleResult("001", "没有检测到人脸", null);
			} else {
			if (baiduyunAPI!=1) {
				return new SimpleResult("002", "检测到多张人脸", null);
			}else {
				int is = fuserService.updateFuser(new Fuser(uId, uName, null, uTel, newImg, null, 1, null, null, null));
				if (is > 0) {
					Fuser fuser= fuserService.getFuserByuId(uId);
					Integer getuId = fuser.getuId();
					String geteSn = fuser.geteSn();
					String getuName = fuser.getuName();
					String getuImg = fuser.getuImg();
					String[] st=geteSn.split("-");
					for (int i = 0; i < st.length; i++) {
						String str="{typr:'deluser',uId:"+getuId+",'uName':"+getuName+",'uImg:'"+getuImg+"}";
						boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
					}
					return new SimpleResult(true);
				} else {
					delFile.del(web.imgurlpath, newImg);
					new SimpleResult("003", "修改失败", null);
				}
			}
			}
		return null;
	}
		/**
		 * 退出登录
		 * @param session
		 * @return
		 */
		@RequestMapping("/logout")
		public  @ResponseBody SimpleResult logout(HttpSession session) {
			if(session!=null){
				Fuser user = (Fuser)session.getAttribute("user");//从当前session中获取用户信息
				session.invalidate();//关闭session
			}
			return new SimpleResult(true);
		}
		/**
		 * 通行记录分页查询
		 */
		@Resource
		private TravelRecordsService TravelRecordsService;
		@RequestMapping("/getAlltravelRecords/{page}")
		public @ResponseBody SimpleResult getAlltravelRecords(@PathVariable("page") int page,HttpSession session) {
			Fuser user=(Fuser)session.getAttribute("user");
			if(user==null)
			{
				return new SimpleResult("001","没有登陆或登陆超时！",null);
			}
			List<TravelRecords> arr = TravelRecordsService.getAlltravelRecords(user.getcId());
			int size = arr.size();
			int pageindex = 0;
			int pagemax;
			if (size % 30 == 0) {
				pagemax = size / 30;
			} else {
				pagemax = size / 30 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) * 30;
			pageselect pageselect=new pageselect(pageindex, 30, null, user.getcId());
			List<TravelRecords> getAlltravelRecordsPage = TravelRecordsService.getAlltravelRecordsPage(pageselect);
			List<travelRecordsBean> beans =new ArrayList<travelRecordsBean>();
			for (TravelRecords t : getAlltravelRecordsPage) {
				Integer getuId = t.getuId();
				Integer getcId = t.getcId();
				String strangerImg = t.getStrangerImg();
				Integer gettId = t.gettId();
				String gettTime = t.gettTime();
				Fuser fuserByuId = fuserService.getFuserByuId(getuId);
				String getuImg = fuserByuId.getuImg();
				Equipment equipmentBySn = equipmentService.getEquipmentBySn(t.geteSn());
				if (equipmentBySn == null || equipmentBySn.equals("")) {
					beans.add(new travelRecordsBean(gettId, gettTime, fuserByuId.getuName(), getcId, strangerImg, getuImg,
							"该设备已删除"));
				} else {
					beans.add(new travelRecordsBean(gettId, gettTime, fuserByuId.getuName(), getcId, strangerImg, getuImg,
							equipmentBySn.geteName()));
				}

			}
			
			return new SimpleResult(beans,pagemax);
		}
		
		@RequestMapping("/getAllstrangerRecordsPage/{page}")
		public @ResponseBody SimpleResult getAllstrangerRecordsPage(@PathVariable("page")int page,HttpSession session) {
			Fuser user=(Fuser)session.getAttribute("user");
			Company companyByCid = companyService.getCompanyByCid(user.getcId());
			String[] st=companyByCid.geteSn().split("-");
			List<String> strarr= new ArrayList<String>();
			for (String s : st) {
				strarr.add(s);
			}
			List<TravelRecords> arr = TravelRecordsService.getAllstrangerRecords(strarr);
			int size = arr.size();
			int pageindex = 0;
			int pagemax;
			if (size % 30 == 0) {
				pagemax = size / 20;
			} else {
				pagemax = size / 20 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) *20;
			List<TravelRecords> allstrangerRecords = new ArrayList<TravelRecords>();
			int count=0;
			for (int i = 0; i < arr.size(); i++) {
				if (i==pageindex||i>pageindex) {
					if(count<20) {
						allstrangerRecords.add(arr.get(i));
						count++;
					}
				}
			}
			
			return new SimpleResult(allstrangerRecords,pagemax);
			
		}
		/**
		 * 获取所有员工打卡记录
		 */
		@Resource
		private AttendanceRecordService  AttendanceRecordService;
		@RequestMapping("/getAttendanceRecord/{y}/{m}")
		public @ResponseBody SimpleResult getAttendanceRecord (@PathVariable("y") int y,@PathVariable("m") int m ,HttpSession session) {
			Fuser user= (Fuser)session.getAttribute("user");
			List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(user.getcId());
			List<getAttendanceRecord> record= new ArrayList<getAttendanceRecord>();
			for (Fuser fuser : fusersAllByCid) {
				Integer cId = user.getcId();
				String uName = fuser.getuName();
				int beLateNum=0;
				int leaveEarlyNum=0;
				AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
				String[] st=attendanceConfigByCid.getWorkday().split("-");
				List<Integer> workday= new ArrayList<Integer>();
				
				for (int i = 0; i < st.length; i++) {
					workday.add(Integer.valueOf(st[i]));
				}
				int oughtToWorkDay=0;
				int oughtToAttendanceNum=0;
				String mt="";
				if (m/10==0) {
					mt="0"+m;
				}else {
					mt=m+"";
				}
				
				List<AttendanceRecord> allAttendanceRecordByUid = AttendanceRecordService.getAllAttendanceRecordByUidandday(new selAttendanceRecord(fuser.getuId(), y+"-"+mt));
				int sumday = WanNianLi.formatCalendarOutput(y,m);
				for (int i = 1; i <= sumday; i++) {
					int getweekDay = WanNianLi.getweekDay(y,m, i);
					for (int j = 0; j < workday.size(); j++) {
						Integer integer = workday.get(j);
						if (integer==getweekDay) {
							oughtToWorkDay++;
						}
					}
					
					for (AttendanceRecord a : allAttendanceRecordByUid) {
						String arTime = a.getArTime();
						String[] date=arTime.split("\\s+");
						String nowdate=y+"-"+mt+"-"+i;
						List<AttendanceRecord> dAttendanceRecords=new ArrayList<AttendanceRecord>();
						if (date[0].equals(nowdate)) {
							dAttendanceRecords.add(a);
						}
						if (dAttendanceRecords.size()!=2) {
							for (AttendanceRecord d : dAttendanceRecords) {
								Integer status = d.getStatus();
								if(status==3) {
									beLateNum++;
								}else if (status==4) {
									leaveEarlyNum++;
								}
							}
						}
					}
				}
				String dString = y + "-" + m;
				oughtToAttendanceNum=oughtToWorkDay*2;
				getAttendanceRecord r = new getAttendanceRecord(fuser.getuId(), uName, oughtToAttendanceNum,
						allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
						oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
				record.add(r);
			}
			return new SimpleResult(record);
		}
		/**
		 * 获取单个用户打卡记录
		 * @param uid
		 * @param y
		 * @param m
		 * @return
		 */
		@RequestMapping("/getAttendanceRecordByUid/{uid}/{y}/{m}")
		public @ResponseBody SimpleResult getAttendanceRecordByUid (@PathVariable("uid")int uid,@PathVariable("y")int y,@PathVariable("m")int m) {
			Fuser user = fuserService.getFuserByuId(uid);
			Integer cId = user.getcId();
			AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
			List<ClockInForDetails> arr = new ArrayList<ClockInForDetails>();
			if (attendanceConfigByCid != null) {

				String[] st = {};
				if (attendanceConfigByCid.getWorkday() != null && !attendanceConfigByCid.getWorkday().equals("")
						&& attendanceConfigByCid.getWorkday().indexOf("-") != -1) {
					st = attendanceConfigByCid.getWorkday().split("-");
				} else {
					st[0] = attendanceConfigByCid.getWorkday();
				}

				String mt = "";
				if (m < 10) {
					mt = "0" + m;
				} else {
					mt = m + "";
				}

				int sumday = WanNianLi.formatCalendarOutput(y, m);

				for (int i = 1; i <= sumday; i++) {
					String nowdate = "";
					if (i < 10) {
						nowdate = y + "-" + mt + "-0" + i;
					} else {
						nowdate = y + "-" + mt + "-" + i;
					}
					List<AttendanceRecord> datadadt = AttendanceRecordService
							.getAllAttendanceRecordByUidandday(new selAttendanceRecord(uid, nowdate));
					if (datadadt.size() == 1) {
						if (datadadt.get(0).getStatus() == 1 || datadadt.get(0).getStatus() == 3) {
							String arTime = datadadt.get(0).getArTime();
							String clockInStatus = "";
							if (datadadt.get(0).getStatus() == 1) {
								clockInStatus = "正常";
							} else if (datadadt.get(0).getStatus() == 3) {
								clockInStatus = "迟到";
							}
							String timeToPunchOut = "无";
							String toPunchOutStatus = "缺勤";
							String isWorkDay = "n";
							String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
							for (int j = 0; j < st.length; j++) {
								String cString = st[j];
								if (cString.equals(getweekDay)) {
									isWorkDay = "y";
								}
							}
							ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, arTime, clockInStatus,
									timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
							arr.add(clockInForDetails);
						} else if (datadadt.get(0).getStatus() == 2 || datadadt.get(0).getStatus() == 4) {
							String timeToPunchOut = datadadt.get(0).getArTime();
							String toPunchOutStatus = "";
							if (datadadt.get(0).getStatus() == 2) {
								toPunchOutStatus = "正常";
							} else if (datadadt.get(0).getStatus() == 4) {
								toPunchOutStatus = "早退";
							}
							String timeToClockIn = "无";
							String clockInStatus = "缺勤";
							String isWorkDay = "n";
							String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
							for (int j = 0; j < st.length; j++) {
								String cString = st[j];
								if (cString.equals(getweekDay)) {
									isWorkDay = "y";
								}
							}
							ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, timeToClockIn,
									clockInStatus, timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
							arr.add(clockInForDetails);
						}
					} else if (datadadt.size() == 2) {
						String timeToClockIn = "";
						String clockInStatus = "";
						String timeToPunchOut = "";
						String toPunchOutStatus = "";
						for (AttendanceRecord att : datadadt) {
							if (att.getStatus() == 1 || att.getStatus() == 3) {
								timeToClockIn += att.getArTime();
								if (att.getStatus() == 1) {
									clockInStatus = "正常";
								} else if (att.getStatus() == 3) {
									clockInStatus = "迟到";
								}
							} else if (att.getStatus() == 2 || att.getStatus() == 4) {
								timeToPunchOut = att.getArTime();
								if (att.getStatus() == 2) {
									toPunchOutStatus = "正常";
								} else if (att.getStatus() == 4) {
									toPunchOutStatus = "早退";
								}
							}
						}
						String isWorkDay = "n";
						String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
						for (int j = 0; j < st.length; j++) {
							String cString = st[j];
							if (cString.equals(getweekDay)) {
								isWorkDay = "y";
							}
						}
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, timeToClockIn, clockInStatus,
								timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					} else if (datadadt.size() == 0) {
						String isWorkDay = "n";
						String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
						for (int j = 0; j < st.length; j++) {
							String cString = st[j];
							if (cString.equals(getweekDay)) {
								isWorkDay = "y";
							}
						}
						if (isWorkDay.equals("y")) {
							ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, "无", "缺勤", "无", "缺勤",
									isWorkDay, y, m, uid);
							arr.add(clockInForDetails);
						} else {
							ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, "无", "无", "无", "无",
									isWorkDay, y, m, uid);
							arr.add(clockInForDetails);
						}
					}
				}

			}
			return new SimpleResult(arr);
		}
		/**
		 * 获取临时密码
		 * @param session
		 * @return
		 * @throws IOException
		 * @throws EncodeException
		 */
		@RequestMapping("/getTemporaryPassword")
		public @ResponseBody SimpleResult  getTemporaryPassword(HttpSession session) throws IOException, EncodeException {
			Random random=new Random();
			String  TemporaryPassword="";
			for (int i = 0; i < 6; i++) {
				String a=random.nextInt(10)+"";
				TemporaryPassword+=a;
			}
			Fuser user=(Fuser)session.getAttribute("user");
			Company companyByCid = companyService.getCompanyByCid(user.getcId());
			String geteSn = companyByCid.geteSn();
			
			if (geteSn!=null&&geteSn!="") {
				if (geteSn.indexOf("-")!=-1) {
					String [] eSnarr=geteSn.split("-");
					for (String esn : eSnarr) {
						String str="{'typr':getTemporaryPassword,TemporaryPassword:"+TemporaryPassword;
						boolean sendInfo = WebSocketServer.sendInfo(str, esn);
					}
				}
			}
			
			return new SimpleResult(TemporaryPassword);
		}
}
